package com.example.rabc.monitor;

import com.example.rabc.common.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * 监控控制器，提供监控数据的查询接口
 */
@RestController
@RequestMapping("/api/monitor")
public class MonitorController {
    private final MetricsAggregator metricsAggregator;
    private final MonitorDataService monitorDataService;

    public MonitorController(MetricsAggregator metricsAggregator,
                             MonitorDataService monitorDataService) {
        this.metricsAggregator = metricsAggregator;
        this.monitorDataService = monitorDataService;
    }

    /**
     * 查询所有方法的平均执行时间
     * @return 包含方法名到平均执行时间的映射
     */
    @GetMapping("/performance/averages")
    public ResponseEntity<ApiResponse<Map<String, Double>>> getAverageExecutionTimes() {
        try {
            Map<String, Double> averages = metricsAggregator.getAverageExecutionTimes();
            return ResponseEntity.ok(ApiResponse.success(averages));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error("Failed to retrieve performance data: " + e.getMessage()));
        }
    }

    /**
     * 查询指定事件类型在时间范围内的监控数据
     * @param eventType 事件类型
     * @param startTime 开始时间戳（包含）
     * @param endTime 结束时间戳（包含）
     * @return 符合条件的监控数据列表
     */
    @GetMapping("/data")
    public ResponseEntity<ApiResponse<List<MonitorData>>> getMonitorData(
            @RequestParam String eventType,
            @RequestParam(required = false) Long startTime,
            @RequestParam(required = false) Long endTime) {

        try {
            Long now = System.currentTimeMillis();
            if (startTime == null) startTime = now - 3600000; // 默认1小时前
            if (endTime == null) endTime = now;

            // 验证时间参数
            if (startTime > endTime) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Start time must be before end time"));
            }

            List<MonitorData> data = monitorDataService.getMonitorData(eventType, startTime, endTime);
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error("Failed to retrieve monitor data: " + e.getMessage()));
        }
    }

    /**
     * 查询指定事件类型的最新监控数据
     * @param eventType 事件类型
     * @param limit 查询数量限制（默认10，最大1000）
     * @return 符合条件的最新监控数据列表
     */
    @GetMapping("/data/recent")
    public ResponseEntity<ApiResponse<List<MonitorData>>> getRecentMonitorData(
            @RequestParam String eventType,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            // 验证limit参数
            if (limit <= 0 || limit > 1000) {
                return ResponseEntity.badRequest().body(ApiResponse.error("Limit must be between 1 and 1000"));
            }

            List<MonitorData> data = monitorDataService.getRecentMonitorData(eventType, limit);
            return ResponseEntity.ok(ApiResponse.success(data));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(ApiResponse.error("Failed to retrieve recent monitor data: " + e.getMessage()));
        }
    }
    /**
     * 健康检查接口，用于验证监控系统是否运行正常
     * @return 包含系统运行状态的响应实体
     */
    @GetMapping("/health")
    public ResponseEntity<ApiResponse<String>> healthCheck() {
        return ResponseEntity.ok(ApiResponse.success("Monitor system is running"));
    }
}